#! /usr/bin/python3
# codings=utf-8
# @time: 2025/10/14 19:01
# @Author:鹤川
import json
import os

import openpyxl
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet

from common.doLog import DoLog

# r反转义
myPath=r'E:\Work\codings\python\2506project\autoTest\datas'
dl=DoLog()
myLogger=dl.getLogger(__name__)
class DoFile:
    # def readTxt(self,fname):
    #     fileName = os.path.join(myPath, fname)
    #     with open(fileName, mode='r', encoding='utf-8') as f:
    #         print(f.read())

    def readTxt(self, fname):
        try:
            myLogger.info(f"开始处理文件{fname}")
            fileName = os.path.join(myPath, fname)
            with open(fileName, mode='r', encoding='utf-8') as f:
                content = f.read()
        except Exception as e:
            print(f"未知错误：{e}")
            myLogger.exception(f"读取文件{fname}失败，原因：{e}")
        else:
            print(content)
            myLogger.info(f"成功读取文件: {fname}")
            return content
        finally:
            # 无论是否发生异常都会执行
            print(f"文件读取操作完成：{fname}")
            myLogger.info(f"文件读取操作完成：{fname}")

    # def writeTxt(self, fname, str1, cls_name, cls_num, cls_type, cls_cj):
    def writeTxt(self, fname,*args):
        fileName = os.path.join(myPath, fname)
        try:
            myLogger.info(f"开始处理文件{fname}")
            with open(fileName, mode='a', encoding='utf-8') as f:
                content = ", ".join(str(arg) for arg in args)
                f.write(content + "\n")
        except Exception as e:
            print(f"写入文件{fname}失败，原因：{e}")
            myLogger.exception(f"写入文件{fname}失败，原因：{e}")
        else:
            print(f"成功写入文件: {fileName}")
            myLogger.info(f"成功写入文件: {fileName}")
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")

    # 字典转json字符串
    def doDictToJsonStr(self,d):
        try:
            myLogger.info(f"开始处理文件{d}")
            jsonStr = json.dumps(d,ensure_ascii=False)
        except Exception as e:
            print(f"未知错误: {e}")
            myLogger.exception(f"字典转换JSON字符串失败，原因：{e}")
        else:
            myLogger.info("字典转换JSON字符串成功")
            print(jsonStr,type(jsonStr))
            return jsonStr
        finally:
            print("字典转换操作完成")
            myLogger.info("字典转换操作完成")

    # json字符串转字典
    def doJsonStrToDict(self,jsonStr):
        try:
            myLogger.info("开始处理文件")
            d = json.loads(jsonStr)
        except Exception as e:
            print(f"未知错误: {e}")
            myLogger.exception(f"JSON字符串转换字典失败，原因：{e}")
        else:
            myLogger.info("JSON字符串转换字典成功")
            print(d,type(d))
            return d
        finally:
            print("JSON转换操作完成")
            myLogger.info("JSON转换操作完成")

    # 字典中内容保存成功json格式文件
    def doDictToJsonFile(self,d,fname):
        fileName = os.path.join(myPath, fname)
        try:
            myLogger.info(f"开始处理文件{fname}")
            with open(fileName, mode='a', encoding='utf-8') as f:
                json.dump(d,f,ensure_ascii=False)
        except Exception as e:
            print(f"保存字典到json文件{fname}失败，原因：{e}")
            myLogger.exception(f"保存字典到json文件{fname}失败，原因：{e}")
        else:
            print(f"成功保存字典到json文件{fname}")
            myLogger.info(f"成功保存字典到json文件{fname}")
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")

    #  json格式文件提取并转成字典
    def doJsonFileToDict(self,fname):
        fileName = os.path.join(myPath, fname)
        try:
            myLogger.info(f"开始处理文件{fname}")
            with open(fileName, mode='r', encoding='utf-8') as f:
                d = json.load(f)
        except Exception as e:
            print(f"读取json文件{fname}失败，原因：{e}")
            myLogger.exception(f"读取json文件{fname}失败，原因：{e}")
        else:
            print(d,type(d))
            myLogger.info(f"成功读取json文件{fname}")
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")

    # 读取Excel文件
    def doExcelRead(self,fname):
        fileName = os.path.join(myPath, fname)
        try:
            myLogger.info(f"开始处理文件{fname}")
            wk:Workbook =openpyxl.load_workbook(fileName)   # 获取工作簿的对象
            st:Worksheet = wk['Sheet1']   # 获取当前活跃的工作表
            print(st,type(st))
            ss=st.iter_rows(values_only=True)
            print(ss)
        except Exception as e:
            print(f"读取Excel文件{fname}失败，原因：{e}")
            myLogger.exception(f"读取Excel文件{fname}失败，原因：{e}")
        else:
            myLogger.info(f"成功读取Excel文件{fname}")
            l=[i for i in ss]
            print(f"{l}")
            return l
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")
            wk.close()  # 关闭工作簿对象

    # 自定义打印Excel内容
    def doExcelReadDIV(self, fname, stname, minRow=None, maxRow=None, minCol=None, maxCol=None):
        # 读取指定Excel文件中的数据，并返回指定范围内的单元格值列表
        fileName = os.path.join(myPath, fname)
        try:
            myLogger.info(f"开始处理文件{fname}")
            wk: Workbook = openpyxl.load_workbook(fileName)  # 获取工作簿的对象
            st: Worksheet = wk[stname]  # 获取当前活跃的工作表
            print(st, type(st))
            ss = st.iter_rows(min_row=minRow, max_row=maxRow, min_col=minCol, max_col=maxCol, values_only=True)
            print(ss)
        except Exception as e:
            print(f"读取Excel文件{fname}失败，原因：{e}")
            myLogger.exception(f"读取Excel文件{fname}失败，原因：{e}")
        else:
            myLogger.info(f"成功读取Excel文件{fname}")
            l = [i for i in ss]
            print(f"{l}")
            return l
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")
            wk.close()  # 关闭工作簿对象

    # 自定义写入Excel文件
    def doExcelWrite(self,fname,stname,data):
        fileName = os.path.join(myPath, fname)  # 定义文件路径  新文件名
        try:
            myLogger.info(f"开始处理文件{fname}")
            wk = openpyxl.Workbook()  # 创建工作簿对象
            st:Worksheet = wk.create_sheet(stname)  # 创建sheet对象
        except Exception as e:
            print(f"创建Excel文件{fname}失败，原因：{e}")
            myLogger.exception(f"创建Excel文件{fname}失败，原因：{e}")
        else:
            myLogger.info(f"成功创建Excel文件{fname}")
            st.cell(1,1,data)  # 写入数据，写一个单元格
            wk.save(fileName)  # 保存文件
        finally:
            print(f"处理{fname}文件时未发生异常")
            myLogger.info(f"处理{fname}文件时未发生异常")
            wk.close()  # 关闭工作簿对象

# 尝试写入一行多行数据，并保存到Excel文件中,列表循环写入

if __name__ == '__main__':
    df = DoFile()
    # Excel写入一行数据
    # df.doExcelWrite("test1.xlsx","Sheet","hello world")

    # Excel读取指定范围内的单元格数据
    # df.doExcelReadDIV("jiaYunSuan.xlsx","Sheet1",2,15,1,1)
    # df.doExcelReadDIV("jiaYunSuan.xlsx","Sheet1",2,15,2,5)

    # df.doExcelReadDIV("jiaYunSuan.xlsx","Sheet2",2,18,2,5)

    # df.doExcelReadDIV("jiaYunSuan.xlsx","Sheet3",2,19,2,5)

    # df.doExcelReadDIV("jiaYunSuan.xlsx","Sheet4",2,20,2,5)

    # Excel读取数据
    # df.doExcelRead("jiaYunSuan.xlsx")

    # d={"name":"张三","age":20,"gender":"男"}

    # 字典转json字符串
    # df.doDictToJsonStr(d)

    # 字典中内容保存成功json格式文件
    # df.doDictToJsonFile(d,"test.json")

    # json格式文件提取并转成字典
    # df.doJsonFileToDict("test.json")

    # json字符串转字典
    # s='{"name":"李四","age":20,"sex":"男"}'
    # df.doJsonStrToDict(s)


    # df.writeTxt("cls1.txt","这是班级模块mym1", "一班",5, "小学", [50, 90, 89, 70, 89, 78])
    # df.writeTxt("cls2.txt","这是班级模块mym2", "二班", 5, "小学", [40,90,100,70,69,77])
    # df.readTxt("cls1.txt")
    # df.readTxt("cls2.txt")



